package org.looop.studio.noots.advantage;

import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.WhitespaceAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.RangeQuery;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.store.Directory;
import org.looop.studio.noots.index.BaseIndexingTestCase;

public class SortingTest extends BaseIndexingTestCase {
	private String[] titles = new String[]{"Thinking in java", "lucene in action", "java concurrent programing in practice"};
	private String[] pubmonth = new String[]{"199501", "199901", "200506"};
	private String[] category = new String[]{"java", "search engine", "concurrency"};
	
	@Override
	protected void addDocuments(Directory dir) throws IOException {
		IndexWriter writer = new IndexWriter(dir, getAnalyzer(), true);
		writer.setUseCompoundFile(isCompund());
		for(int i=0; i < titles.length; i++){
			Document doc = new Document();
			doc.add(Field.Text("title", titles[i]));
			doc.add(Field.Text("pubmonth", pubmonth[i]));
			doc.add(Field.Keyword("category", category[i]));
			writer.addDocument(doc);
		}
		writer.optimize();
		writer.close();
	}
	
	@Override
	protected Analyzer getAnalyzer() {
		return new WhitespaceAnalyzer();
	}
	
	public void testSearchResultViewer() throws Exception {
		SearchResultViewer searchResultViewer = new SearchResultViewer(dir);
		Query allBooks = new RangeQuery(new Term("pubmonth", "197001"), new Term("pubmonth", "201301"), true);
		searchResultViewer.displayHits(allBooks, null);
		searchResultViewer.displayHits(allBooks, Sort.RELEVANCE);
		searchResultViewer.displayHits(allBooks, new Sort("category"));
		searchResultViewer.displayHits(allBooks, new Sort("pubmonth"));
		
		searchResultViewer.displayHits(allBooks, new Sort("category", true));
		searchResultViewer.displayHits(allBooks, new Sort(
			new SortField[]{new SortField("category"), SortField.FIELD_SCORE, new SortField("pubmonth", SortField.INT, true)}
		));
		
	}
}
